package thinkingInJava.concurrency;
// page 700
//: concurrency/Interrupting2.java
// Interrupting a task blocked with a ReentrantLock.
import java.util.concurrent.*;
import java.util.concurrent.locks.*;
import static thinkingInJava.YTool.YPrint.*;

class BlockedMutex {
	private Lock lock = new ReentrantLock();
	public BlockedMutex() {
		// Acquire it right away, to demonstrate interruption
		// of a task blocked on a ReentrantLock:
		lock.lock();
	}
	public void f() {
//		lock.lock(); // 如果用这个则阻塞时f()无法中断
		try {
			// This will never be available to a second task
			lock.lockInterruptibly(); // 这个相当于阻塞时也可中断的 lock() 版本
			print("lock acquired in f()");
		} catch(InterruptedException e) {
			print("Interrupted from lock acquisition in f()");
		}
		print("end in f()");
	}
}

class Blocked2 implements Runnable {
	BlockedMutex blocked = new BlockedMutex();
	public void run() {
		print("Waiting for f() in BlockedMutex");
		blocked.f();
		print("Broken out of blocked call");
	}
}

public class Interrupting2 {
	public static void main(String[] args) throws Exception {
		Thread t = new Thread(new Blocked2());
		t.start();
		TimeUnit.SECONDS.sleep(1);
		System.out.println("Issuing t.interrupt()");
		t.interrupt();
	}
} /* Output:
Waiting for f() in BlockedMutex
Issuing t.interrupt()
Interrupted from lock acquisition in f()
Broken out of blocked call
 *///:~
